package br.biofoco.p2p.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class SimpleGUI extends JFrame implements ActionListener {

	private static final long serialVersionUID = 8969200787593362904L;
	private final JTextField filename = new JTextField(32);
	private final JButton open = new JButton("...");
	private final JButton submit = new JButton("Submit");
	private final JCheckBox checkbox = new JCheckBox("Torrent");
	private final JCheckBox checkbox2 = new JCheckBox("sftp");
	private final Controller controller;
	private File file;

	public SimpleGUI(Controller controller) {

		this.controller = controller;

		this.setSize(500, 100);
		this.setLocation(400, 400);
		this.setTitle("BLAST Runner");
		this.setResizable(false);

		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});

		open.addActionListener(this);
		submit.addActionListener(this);
		this.add(new GuiPanel());
	}

	private class GuiPanel extends JPanel {

		private static final long serialVersionUID = -5685697211646359896L;

		public GuiPanel() {
			add(filename);
			add(open);
			add(submit);
			add(checkbox);
			add(checkbox2);
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getSource() == open) {
			JFileChooser.setDefaultLocale(new Locale("PT-BR"));
			JFileChooser j = new JFileChooser();

			j.setFileSelectionMode(JFileChooser.FILES_ONLY);

			int returnVal = j.showOpenDialog(this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				file = j.getSelectedFile();
				filename.setText(file.getAbsolutePath());
			}
		}
		
		if (e.getSource() == submit) {
			
			if (filename.getText() == null || filename.getText().trim().length() == 0) {
				JOptionPane.showMessageDialog(this, "Please, select a valid file");
				return;
			}
			
			if (checkbox.isSelected()) {
				controller.submitTorrent(file);
			} else if (checkbox2.isSelected()){
				controller.submitTaskSFTP(new File(filename.getText()));
			}
			else {
				controller.submit(file);
			}
		}
	}
}
